const db = require('../db')
const jwt = require('jsonwebtoken')

const secretKey = 'isomer 1229 ^.^'

exports.login = (req, res) => {
  const { phone, password } = req.query
  
  // 查找 phone
  const selectUserPhone = 'select * from easy_chat.users where phone = ?'
  db.query(selectUserPhone, phone, (err, results) => {
    if (err) {
      return res.errHandle(err)
    }

    if (results.length < 1) {
      return res.errHandle('电话号不存在')
    }

    if (results[0].password !== password) {
      return res.errHandle('密码错误')
    }

    // 生成 token
    const token = jwt.sign({ phone: phone }, secretKey, {
      expiresIn: '1d' // 有效期 1d
    })

    res.send({
      code: 200,
      message: 'success',
      data: {
        token,
        wx_id: results[0].wx_id,
        phone: results[0].phone,
        nickname: results[0].nickname,
        signature: results[0].signature,
        avatar_url: results[0].avatar_url,
      }
    })
  })
}

exports.register = (req, res) => {
  const { phone, wx_id, password } = req.query

  // 判断微信号和电话号是否重复
  const selectPhone = 'select phone from easy_chat.users where phone = ?'
  db.query(selectPhone, phone, (err, results) => {
    if (err) res.errHandle(err)
    
    if (results.length > 0) {
      res.send({
        code: 200,
        message: 'fail',
        data: {
          message: '手机号已被注册'
        }
      })
    } else {
      const selectWxId = 'select wx_id from easy_chat.users where wx_id = ?'
      db.query(selectWxId, wx_id, (err, results) => {
        if (err) res.errHandle(err)
        
        if (results.length > 0) {
          res.send({
            code: 200,
            message: 'fail',
            data: {
              message: '微信号已被占用'
            }
          })
        } else {
          const registerUser = 'insert into easy_chat.users set ?'
          db.query(registerUser, { wx_id, nickname: '用户' + wx_id, password, phone, avatar_url: 'https://avatars.githubusercontent.com/u/99958139' }, (err, result) => {
            if (err) res.errHandle(err)

            const token = jwt.sign({ phone: phone }, secretKey, {
              expiresIn: '1d' // 有效期 1d
            })

            res.send({
              code: 200,
              message: 'success',
              data: {
                token,
                wx_id,
                phone,
                nickname: '用户' + wx_id,
                signature: '',
                avatar_url: 'https://avatars.githubusercontent.com/u/99958139',
              }
            })
          })
        }
      })
    }
  })
}
